﻿using System.Windows;
using System.Windows.Input;
using DevExpress.Mvvm;
using EduAssess.Services;

namespace EduAssess.ViewModels;

public class TestDialogWindowViewModel : BindableBase
{
    private readonly TestState _testState;
    private int _questionNumber;

    public int QuestionNumber
    {
        get => _questionNumber;
        set
        {
            if (value < 0)
            {
                _questionNumber = 0;
            }
            else if (value > MaxQuestionNum)
            {
                _questionNumber = MaxQuestionNum;
            }
            else
            {
                _questionNumber = value;
            }
        }
    }

    public int MaxQuestionNum { get; set; }
    public bool MixQuestions { get; set; }
    public bool MixAnswers { get; set; }
    private int _startIntervalNum;

    public int StartIntervalNum
    {
        get => _startIntervalNum;
        set
        {
            if (value < 1 || value > MaxQuestionNum || value > EndIntervalNumber)
                _startIntervalNum = 1;
            else _startIntervalNum = value;
        }
    }

    private int _endIntervalNumber;

    public int EndIntervalNumber
    {
        get => _endIntervalNumber;
        set
        {
            if (value < 1 || value > MaxQuestionNum || value < StartIntervalNum)
            {
                _endIntervalNumber = MaxQuestionNum;
            }
            else
            {
                _endIntervalNumber = value;
            }
        }
    }

    public bool CanCheckAnswers { get; set; }

    public TestDialogWindowViewModel(TestState testState)
    {
        _testState = testState;
        StartIntervalNum = 1;
        if (_testState.CurrentTest != null)
            QuestionNumber = EndIntervalNumber = MaxQuestionNum = _testState.CurrentTest.QuestionCount;
        MixQuestions = MixAnswers = CanCheckAnswers = true;
    }

    public ICommand ContinueCommand => new DelegateCommand<Window>((win) =>
    {
        _testState.ChangeTestParameters(StartIntervalNum, EndIntervalNumber, QuestionNumber, MixQuestions, MixAnswers);
        _testState.CanCheckAnswer = CanCheckAnswers;
        win.DialogResult = true;
    }, (_) => QuestionNumber > 0);

    public ICommand SetMaxCommand => new DelegateCommand(() => { QuestionNumber = MaxQuestionNum; });

    public ICommand SetMaxIntervalCommand => new DelegateCommand(() => { EndIntervalNumber = MaxQuestionNum; });

    public ICommand SetMinCommand => new DelegateCommand(() => { StartIntervalNum = 1; });
}